var bookVideoDisplayBoolean = false;

$(function () {
    //初始化教辅书静态数据
    vm.initBookList();
    //初始化视频静态数据
    //vm.initBookVideo();
    //加载教辅书数据
    vm.reload();
    vm.getDictList(function () {
        vm.addSelected();
    });
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        showBookVideo: false,
        title: null,
        book: {
            grade: {},
            subject: {},
            version: {},
            fascicle: {},
            season: {},
            gradeId: -1,
            seasonId: -1,
            subjectId: -1,
            versionId: -1,
            fascicleId: -1
        },
        bookVideo: {
            book: {grade: {}, subject: {}, version: {}, fascicle: {}, season: {}}
        },
        showBook: {},
        gradeList: [],
        subjectList: [],
        versionList: [],
        fascicleList: [],
        seasonList: [],
        q: {
            key: null
        },
        status: -1
    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.getDictList(function () {
                vm.book = {
                    gradeId: vm.gradeList[0].id,
                    seasonId: vm.seasonList[0].id,
                    subjectId: vm.subjectList[0].id,
                    versionId: vm.versionList[0].id,
                    fascicleId: vm.fascicleList[0].id,
                };
            });
        },
        update: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id);
            vm.getDictList(function () {
            });
        },
        saveOrUpdate: function (event) {
            var url = vm.book.id == null ? "../book/save" : "../book/update";
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                data: JSON.stringify(vm.book),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: "../book/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function (id) {
            $.get("../book/info/" + id, function (r) {
                vm.book = r.book;
            });
        },
        getDictList: function (handler) {
            $.get("../dictionary/list4Show", function (r) {
                vm.gradeList = r.dictionaryList.filter(dirctionary => dirctionary.type === "T01");
                vm.subjectList = r.dictionaryList.filter(dirctionary => dirctionary.type === "T02");
                vm.versionList = r.dictionaryList.filter(dirctionary => dirctionary.type === "T03");
                vm.fascicleList = r.dictionaryList.filter(dirctionary => dirctionary.type === "T04");
                vm.seasonList = r.dictionaryList.filter(dirctionary => dirctionary.type === "T05");
                handler();
            });
        },
        addSelected: function () {
            vm.gradeList.unshift({id: -1, name: "选择年级"});
            vm.subjectList.unshift({id: -1, name: "选择科目"});
            vm.versionList.unshift({id: -1, name: "选择教版"});
            vm.fascicleList.unshift({id: -1, name: "选择册别"});
            vm.seasonList.unshift({id: -1, name: "选择年季"});
        },
        //跳转视频管理
        videoManage: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            var rowId = $("#jqGrid").jqGrid("getGridParam", "selrow");
            vm.showBook = $("#jqGrid").jqGrid('getRowData', rowId);
            vm.showBookVideo = true;
            vm.reload4BookVideo();

        },
        clearJqGrid: function () {
            var postData = $('#jqGrid').jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
        },
        goback: function () {
            vm.book = {
                gradeId: -1,
                seasonId: -1,
                subjectId: -1,
                versionId: -1,
                fascicleId: -1
            };
            vm.status= -1;
            vm.addSelected();
            vm.reload();
        },
        publish: function (event) {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }
            confirm('确定要审核选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: "../book/publish",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                vm.reload();
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        remove: function (event) {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }
            confirm('确定要反审核选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: "../book/remove",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                vm.reload();
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        reload: function (event) {
            vm.showList = true;
            vm.showBookVideo = false;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');

            let postdata = '{ "a":"a"';
            if (vm.book.gradeId != "-1" && vm.book.gradeId != undefined) {
                postdata += ',"gradeId": ' + vm.book.gradeId
            }
            if (vm.book.subjectId != "-1" && vm.book.subjectId != undefined) {
                postdata += ',"subjectId": ' + vm.book.subjectId
            }
            if (vm.book.versionId != "-1" && vm.book.versionId != undefined) {
                postdata += ',"versionId": ' + vm.book.versionId
            }
            if (vm.book.fascicleId != "-1" && vm.book.fascicleId != undefined) {
                postdata += ',"fascicleId": ' + vm.book.fascicleId
            }
            if (vm.book.seasonId != "-1" && vm.book.seasonId != undefined) {
                postdata += ',"seasonId": ' + vm.book.seasonId
            }
            if (vm.status != "-1" && vm.status != undefined) {
                postdata += ',"status": ' + vm.status
            }
            postdata += "}";
            vm.clearJqGrid();
            $("#jqGrid").jqGrid('setGridParam', {
                datatype: "json",
                postData: $.parseJSON(postdata),
                page: page
            }).trigger("reloadGrid");

        },

        //批量导入
        upload4BookVideo: function (e) {
            var file = e.target.files[0];
            var form = new FormData();
            form.append("file", file);
            var fileName = file.name;
            if (fileName === '') {
                alert("请选择文件");
                return;
            }
            var fileType = (fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length)).toLowerCase();
            if (fileType !== 'xls' && fileType !== 'xlsx') {
                alert("文件格式不正确，Excel文件！");
                return;
            }
            $.ajax({
                url: "../bookvideo/importVideo/" + vm.showBook.id,
                data: form,
                type: "POST",
                processData: false,
                contentType: false,
                success: function (r) {
                    e.target.value = '';
                    if (r.code === 0) {
                        alert(r.msg);
                        vm.reload4BookVideo();
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        //查询教辅书视频
        query4BookVideo: function () {
            vm.reload4BookVideo();
        },
        //添加教辅书视频
        add4BookVideo: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.bookVideo = {
                book: {grade: {}, subject: {}, version: {}, fascicle: {}, season: {}},
                bookId: vm.showBook.id
            };
        },
        //修改教辅书视频信息
        update4BookVideo: function (event) {
            var id = vm.getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo4BookVideo(id)
        },
        //保存或更新教辅书视频信息
        saveOrUpdate4BookVideo: function (event) {
            var url = vm.bookVideo.id == null ? "../bookvideo/save" : "../bookvideo/update";
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                data: JSON.stringify(vm.bookVideo),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload4BookVideo();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        //删除教辅书视频
        del4BookVideo: function (event) {
            var ids = vm.getSelectedRows();
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: "../bookvideo/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid4BookVideo").jqGrid('setGridParam', {
                                    datatype: 'json'
                                }).trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },

        //获取教辅书视频信息
        getInfo4BookVideo: function (id) {
            $.get("../bookvideo/info/" + id, function (r) {
                vm.bookVideo = r.bookVideo;
            });
        },

        //加载视频数据
        reload4BookVideo: function (event) {
            vm.showList = true;
            vm.showBookVideo = true;
            if(!bookVideoDisplayBoolean){
                vm.initBookVideo();
                bookVideoDisplayBoolean=true;
            }
            var page = $("#jqGrid4BookVideo").jqGrid('getGridParam', 'page');
            $("#jqGrid4BookVideo").jqGrid('setGridParam', {
                datatype: 'json',
                page: page,
                postData: {
                    bookId: vm.showBook.id,
                    key: vm.q.key,
                }
                //设置教辅书数据
            }).trigger("reloadGrid");
        },

        publish4BookVideo: function (event) {
            var ids = vm.getSelectedRows();
            if (ids == null) {
                return;
            }
            confirm('确定要审核选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: "../bookvideo/publish",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                vm.reload4BookVideo();
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        remove4BookVideo: function (event) {
            var ids = vm.getSelectedRows();
            if (ids == null) {
                return;
            }
            confirm('确定要反审核选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: "../bookvideo/remove",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                vm.reload4BookVideo();
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },

        //初始化教辅书列表
        initBookList: function () {
            $("#jqGrid").jqGrid({
                url: '../book/list',
                datatype: "local",
                colModel: [
                    {label: 'id', name: 'id', index: 'id', width: 50, key: true},
                    {label: '教辅书名称', name: 'name', index: 'name', width: 80},
                    {label: '教辅书标题', name: 'title', index: 'title', width: 80},
                    {label: '教辅书描述', name: 'description', index: 'description', width: 80},
                    {label: '教辅书答案地址', name: 'answerUrl', index: 'answer_url', width: 80},
                    {label: '教辅书封面地址', name: 'coverUrl', index: 'cover_url', width: 80},
                    {label: '教辅书编号', name: 'isbn', index: 'isbn', width: 80},
                    {label: '教辅书顺序', name: 'orderField', index: 'order_field', width: 80},
                    {
                        label: '年级', name: 'grade', index: 'grade', width: 80,
                        formatter: function (value, options, row) {
                            if (value != null) {
                                return value.name;
                            } else {
                                return "";
                            }
                        }
                    },
                    {
                        label: '科目', name: 'subject', index: 'subject', width: 80,
                        formatter: function (value, options, row) {
                            if (value != null) {
                                return value.name;
                            } else {
                                return "";
                            }
                        }
                    },
                    {
                        label: '教版', name: 'version', index: 'version', width: 80,
                        formatter: function (value, options, row) {
                            if (value != null) {
                                return value.name;
                            } else {
                                return "";
                            }
                        }
                    },
                    {
                        label: '册别', name: 'fascicle', index: 'fascicle', width: 80,
                        formatter: function (value, options, row) {
                            if (value != null) {
                                return value.name;
                            } else {
                                return "";
                            }
                        }
                    },
                    {
                        label: '年季', name: 'season', index: 'season', width: 80,
                        formatter: function (value, options, row) {
                            if (value != null) {
                                return value.name;
                            } else {
                                return "";
                            }
                        }
                    },
                    {label: '创建时间', name: 'createTime', index: 'create_time', width: 80},
                    {label: '修改时间', name: 'updateTime', index: 'update_time', width: 80},
                    {
                        label: '审核状态', name: 'status', index: 'status', width: 80,
                        formatter: function (value, options, row) {

                            if (value == 0) {
                                return "未审核";
                            } else if (value == 1) {
                                return "审核已通过";
                            } else {
                                return "审核未通过";
                            }
                        }
                    },
                    {
                        label: '是否删除', name: 'deleted', index: 'deleted', width: 80,
                        formatter: function (value, options, row) {
                            if (value == 0) {
                                return "否";
                            } else {
                                return "是";
                            }
                        }
                    }
                ],
                viewrecords: true,
                height: 385,
                rowNum: 10,
                rowList: [10, 30, 50],
                rownumbers: true,
                rownumWidth: 50,
                autowidth: true,
                multiselect: true,
                pager: "#jqGridPager",
                jsonReader: {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames: {
                    page: "page",
                    rows: "limit",
                    order: "order"
                },
                gridComplete: function () {
                    //隐藏grid底部滚动条
                    $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
                }
            });
        },

        //初始化教辅书视频
        initBookVideo: function () {
            jQuery("#jqGrid4BookVideo").jqGrid("clearGridData");
            $("#jqGrid4BookVideo").jqGrid({
                url: '../bookvideo/list',
                datatype: "local",
                colModel: [
                    {label: 'id', name: 'id', index: 'Id', width: 50, key: true},
                    {label: '单元名称', name: 'unitName', index: 'unit_name', width: 80},
                    {label: '页码', name: 'pageNo', index: 'page_no', width: 40},
                    {label: '视频名称', name: 'videoName', index: 'video_name', width: 80},
                    {
                        label: '视频地址', name: 'videoUrl', index: 'video_url', width: 200,
                        formatter: function (value, options, row) {
                            let bookVideoHtml = '<div><a class="btn btn-primary" onclick="alert(' + "点击了上传方法" + ')">上传</a>';
                            if (value != null && value.trim() != "") {
                                bookVideoHtml += '<a class="btn btn-primary" href="' + value + '" target="view_window">查看</a>';
                            }
                            return bookVideoHtml += '</div>';
                        }
                    },
                    {label: '二维码场景值', name: 'qrcodeNo', index: 'qrcode_no', width: 80},
                    {
                        label: '二维码地址', name: 'qrcodeUrl', index: 'qrcode_url', width: 80,
                        formatter: function (value, options, row) {
                            let qrcodeHtml = '<div>';
                            if (value != null && value.trim() != "") {
                                qrcodeHtml += '<a class="btn btn-primary" href="' + value + '" target="view_window">预览</a>';
                            }
                            return qrcodeHtml += '</div>';
                        }
                    },
                    {label: '描述', name: 'description', index: 'description', width: 80},
                    {label: '排序字段', name: 'orderField', index: 'order_field', width: 80},
                    {label: '创建时间', name: 'createTime', index: 'create_time', width: 80},
                    {label: '修改时间', name: 'updateTime', index: 'update_time', width: 80},
                    {
                        label: '审核状态', name: 'status', index: 'status', width: 80,
                        formatter: function (value, options, row) {

                            if (value == 0) {
                                return "未审核";
                            } else if (value == 1) {
                                return "审核已通过";
                            } else {
                                return "审核未通过";
                            }
                        }
                    },
                    {
                        label: '是否删除', name: 'deleted', index: 'deleted', width: 80,
                        formatter: function (value, options, row) {
                            if (value == 0) {
                                return "否";
                            } else {
                                return "是";
                            }
                        }
                    },
                ],
                viewrecords: true,
                height: 385,
                rowNum: 10,
                rowList: [10, 30, 50],
                rownumbers: true,
                rownumWidth: 50,
                autowidth: true,
                multiselect: true,
                pager: "#jqGridPager4BookVideo",
                jsonReader: {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames: {
                    page: "page",
                    rows: "limit",
                    order: "order"
                },
                gridComplete: function () {
                    //隐藏grid底部滚动条
                    $("#jqGrid4BookVideo").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
                }
            });
        },
        getSelectedRow: function () {
            var grid = $("#jqGrid4BookVideo");
            var rowKey = grid.getGridParam("selrow");
            if (!rowKey) {
                alert("请选择一条记录");
                return;
            }

            var selectedIDs = grid.getGridParam("selarrrow");
            if (selectedIDs.length > 1) {
                alert("只能选择一条记录");
                return;
            }

            return selectedIDs[0];
        },
        getSelectedRows: function () {
            var grid = $("#jqGrid4BookVideo");
            var rowKey = grid.getGridParam("selrow");
            if (!rowKey) {
                alert("请选择一条记录");
                return;
            }

            return grid.getGridParam("selarrrow");
        }
    }
});